 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=91 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Clarifying method
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='document,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Clarifying method</div>

<div class='main-body'>
 
<br>The structure of a method can often be made clearer by splitting it
up into smaller methods. Martin Fowler, author of <i>Refactoring</i>, is
an enthusiastic advocate of this style.
<p>Refactoring an original method into smaller pieces has several advantages:
<ul>
<li>
it allows the original method to stay at a higher level of abstraction,
which always increases legibility</li>

<li>
it makes the original method simpler</li>

<li>
it reduces the number of local variables in the original method</li>

<li>
it allows method names to automatically document the intent of the code</li>
</ul>
Sometimes a comment is placed at the start of a chunk of code, explaining
its intent. If a clarifying method is used instead, then the chunk of code
gets refactored into its own method, while the comment itself is replaced
by a call to a well named method. "<i>When a comment grows up, it becomes
a method call</i>".
<p><b>Example</b>
<p>Here, the method <tt>parseSearchText</tt>, which was originally monolithic,
has been refactored to call several <tt>private</tt> methods which perform
very well defined, simple tasks.
<p>Boolean conditions can often benefit from being placed in their own
method. Here, <tt>isDoubleQuote</tt>, <tt>isCommonWord</tt>, and <tt>textHasContent</tt>
are all examples of this.
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='comment'>/**
* The user enters text into a search box. This class is used
* to parse that text into specific search terms (or tokens).
* It eliminates common words, and allows for the quoting of text, using
* double quotes.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> SearchBoxParser {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArguments) {
    SearchBoxParser parser = <span class='keyword'>new</span> SearchBoxParser( <span class='literal'>"mars venus &#092;"milky way&#092;" sun"</span> );
    Set&lt;String&gt; tokens = parser.parseSearchText();
    <span class='comment'>//display the tokens
</span>    System.out.println(tokens);
  }

  <span class='comment'>/**
  * @param aSearchText is non-null, but may have no content,
  * and represents what the user has input in a search box.
  */</span>
  <span class='keyword'>public</span> SearchBoxParser( String aSearchText ) {
    <span class='keyword'>if</span> ( aSearchText == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Search Text cannot be null."</span>);
    }
    fSearchText = aSearchText;
  }

  <span class='comment'>/**
  * Parse the user's search box input into a Set of String tokens.
  *
  * @return Set of Strings, one for each word in fSearchText; here "word"
  * is defined as either a lone word surrounded by whitespace, or as a series
  * of words surrounded by double quotes, "like this"; also, very common
  * words (and, the, etc.) do not qualify as possible search targets.
  */</span>
  <span class='keyword'>public</span> Set&lt;String&gt; parseSearchText() {
    Set&lt;String&gt; result = <span class='keyword'>new</span> HashSet&lt;String&gt;();

    <span class='keyword'>boolean</span> returnTokens = <span class='keyword'>true</span>;
    String currentDelims = fWHITESPACE_AND_QUOTES;
    StringTokenizer parser = <span class='keyword'>new</span> StringTokenizer(
      fSearchText,
      currentDelims,
      returnTokens
    );

    String token = <span class='keyword'>null</span>;
    <span class='keyword'>while</span> ( parser.hasMoreTokens() ) {
      token = parser.nextToken(currentDelims);
      <span class='keyword'>if</span> ( !isDoubleQuote(token) ){
        addNonTrivialWordToResult( token, result );
      }
      <span class='keyword'>else</span> {
        currentDelims = flipDelimiters(currentDelims);
      }
    }
    <span class='keyword'>return</span> result;
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> String fSearchText;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Set&lt;String&gt; fCOMMON_WORDS = <span class='keyword'>new</span> HashSet&lt;String&gt;();
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fDOUBLE_QUOTE = <span class='literal'>"&#092;""</span>;

  <span class='comment'>//the parser flips between these two sets of delimiters
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fWHITESPACE_AND_QUOTES = <span class='literal'>" &#092;t&#092;r&#092;n&#092;""</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fQUOTES_ONLY =<span class='literal'>"&#092;""</span>;

  <span class='comment'>/**
  * Very common words against which searches will not be
  * performed.
  */</span>
  <span class='keyword'>static</span> {
    fCOMMON_WORDS.add(<span class='literal'>"a"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"and"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"be"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"for"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"from"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"has"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"i"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"in"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"is"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"it"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"of"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"on"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"to"</span>);
    fCOMMON_WORDS.add(<span class='literal'>"the"</span>);
  }

  <span class='comment'>/**
  * Use to determine if a particular word entered in the
  * search box should be discarded from the search.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> isCommonWord( String aSearchTokenCandidate ) {
    <span class='keyword'>return</span> fCOMMON_WORDS.contains(aSearchTokenCandidate);
  }

  <span class='keyword'>private</span> <span class='keyword'>boolean</span> textHasContent(String aText) {
    <span class='keyword'>return</span> (aText != <span class='keyword'>null</span>) &amp;&amp; (!aText.trim().equals(<span class='literal'>""</span>));
  }

  <span class='keyword'>private</span> <span class='keyword'>void</span> addNonTrivialWordToResult( String aToken, Set&lt;String&gt; aResult ){
    <span class='keyword'>if</span> ( textHasContent(aToken) &amp;&amp; !isCommonWord(aToken.trim()) ) {
      aResult.add( aToken.trim() );
    }
  }

  <span class='keyword'>private</span> <span class='keyword'>boolean</span> isDoubleQuote( String aToken ){
    <span class='keyword'>return</span> aToken.equals(fDOUBLE_QUOTE);
  }

  <span class='keyword'>private</span> String flipDelimiters( String aCurrentDelims ) {
    String result = <span class='keyword'>null</span>;
    <span class='keyword'>if</span> ( aCurrentDelims.equals(fWHITESPACE_AND_QUOTES) ) {
      result = fQUOTES_ONLY;
    }
    <span class='keyword'>else</span> {
      result = fWHITESPACE_AND_QUOTES;
    }
    <span class='keyword'>return</span> result;
  }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction56bf-2.html?Id=227'>Avoid basic style errors</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='91'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=91 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
